<template>
  <view class="register">
    <!-- #ifndef MP-WEIXIN -->
    <c-navbar
      v-if="info && info.parent == ''"
      title=""
      fixed
      style="margin-left: -60rpx"
    ></c-navbar>
    <view v-else class="c-navbar-no"></view>
    <!-- #endif -->
    <view class="register-title">快速注册账号</view>

    <view class="form-v2">
      <view class="login-input betweenBox">
        <view class="prefix">
          <picker
            class="country-code"
            :value="countryCodeIndex"
            :range="countryCodeTxtAndCodeList"
            @change="countryCodeChange"
          >
            <view class="picker">
              {{ countryCodeTxtList[countryCodeIndex] || '' }}
            </view>
          </picker>
        </view>
        <view class="input-warp">
          <input
            v-model="info.mobilePhone"
            type="number"
            class="ipt"
            placeholder="请输入手机号码"
          />
        </view>
        <view class="addon">
          <server-image
            v-if="info.mobilePhone"
            class="del-icon disb"
            name="loginIcon20201020002.png"
            mode="aspectFill"
            @click="info.mobilePhone = ''"
          ></server-image>
        </view>
      </view>

      <view class="login-input betweenBox">
        <view class="input-warp">
          <input v-model="info.imgCode" class="ipt" placeholder="请输入图形验证码" />
        </view>
        <view class="addon">
          <c-image
            class-name="img-code disb"
            :src="imgCodePath"
            mode="aspectFit"
            @click="initImgCode"
          ></c-image>
        </view>
      </view>

      <view class="login-input betweenBox">
        <view class="input-warp">
          <input v-model="info.smsCode" class="ipt" placeholder="请输入手机验证码" />
        </view>
        <view class="addon">
          <view class="addon-warp flex-box">
            <view class="v-code" :class="{ deny: !allowGetCode }" @click="getCode">
              <text v-if="allowGetCode">获取验证码</text>
              <text v-else>重新发送{{ countDown }}S</text>
            </view>
          </view>
        </view>
      </view>

      <view class="login-input betweenBox">
        <view class="input-warp">
          <input
            v-model="info.password"
            class="ipt"
            placeholder="6-16位字母数字组合登录密码"
            :password="!showPassword"
          />
        </view>
        <view class="addon">
          <view class="addon-warp flex-box" @tap="showPassword = !showPassword">
            <server-image
              v-if="!showPassword"
              class="visible-icon disb"
              name="publicInputIconHide.png"
              mode="aspectFill"
            ></server-image>
            <server-image
              v-else
              class="visible-icon disb"
              name="publicInputIconDisplay.png"
              mode="aspectFill"
            ></server-image>
          </view>
        </view>
      </view>

      <view class="login-input betweenBox">
        <view class="input-warp">
          <input
            v-model="info.parent"
            class="ipt"
            placeholder="请输入邀请码(选填)"
            :disabled="parentReadOnly"
          />
        </view>
      </view>
    </view>

    <view class="agreement">
      <view class="agreement-checkbox" @tap="agree = !agree">
        <server-image v-if="agree" class="icon disb" name="img20210909002.png"></server-image>
        <server-image v-else class="icon disb" name="img20210909001.png"></server-image>
      </view>
      <!--      <navigator url="agreements/agreements?type=1" hover-class="none">-->
      <!--        <text>我已阅读并同意<text class="underline">《广州商科注册协议》</text><text class="underline">《隐私协议》</text></text>-->
      <!--      </navigator>-->
      <view>
        <text style="margin-left: 20rpx">我已阅读并同意</text>
        <text class="underline" @click="toPage('agreements/agreements?type=1')">
          《广州商科注册协议》
        </text>
        <text>与</text>
        <text class="underline" @click="toRule('隐私协议', 15)">《隐私协议》</text>
      </view>
    </view>

    <view class="login-submit" @click="register">完成注册</view>
  </view>
</template>

<script>
import config from '@/common/config';
import { mapState, mapActions } from 'vuex';
import cNavbar from '@/components/c-navbar';
import { isObject } from '@/common/utils';

export default {
  components: { cNavbar },
  data() {
    return {
      info: {
        mobilePhone: '',
        smsCode: '',
        imgCode: '',
        password: '',
        paypwd: '',
        parent: '',
      },
      showPassword: false,
      imgCodePath: '',
      key: '',
      allowGetCode: true,
      countDown: 60,
      agree: false,
      apiLoading: false,
      countryCodeIndex: 0,
      parentReadOnly: false,
      isFormEnter: false,
      formPage: '',
      fromPaetnerINtroduction: false,
      smsCodeTimer: null,
    };
  },
  onLoad(e) {
    this.fromPaetnerINtroduction = uni.getStorageSync('fromPaetnerINtroduction');
    let memberAutoId = uni.getStorageSync('memberAutoId');
    e.agree ? (this.agree = true) : '', this.initImgCode();
    e.autoId && e.autoId != 'undefined' ? (memberAutoId = e.autoId) : '';
    e.form && e.form != 'undefined' ? (this.formPage = e.form) : '';
    this.isFormEnter = uni.getStorageSync('formEnter');

    if (memberAutoId && memberAutoId != 'undefined') {
      this.info.parent = memberAutoId;
      this.parentReadOnly = true;
    }
  },
  onShow() {
    const vm = this;
    if (uni.getStorageSync('fromRegisterUccess')) {
      uni.removeStorageSync('fromRegisterUccess');
      uni.navigateTo({
        url: 'login',
      });
    }
    uni.getStorage({
      key: 'agreeRegister',
      success: (res) => {
        vm.agree = res.data;
        uni.removeStorageSync('agreeRegister');
      },
    });

    this.getCountryList();
  },
  computed: {
    ...mapState({
      countryCodeList: (state) => state.countryCode || [],
    }),
    countryCodeTxtAndCodeList: function () {
      return this.countryCodeList.map((v) => `${v.countryName} ${v.countryCode}`);
    },
    countryCodeTxtList: function () {
      return this.countryCodeList.map((v) => v.countryCode);
    },
    countryCode: function () {
      return this.countryCodeTxtList[this.countryCodeIndex];
    },
  },
  methods: {
    ...mapActions(['getCountryList']),
    countryCodeChange(e) {
      this.countryCodeIndex = e.detail.value;
    },
    register() {
      if (!this.info.mobilePhone) {
        uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '请输入手机号码',
        });
        return;
      }
      if (!this.info.smsCode) {
        uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '请输入手机验证码',
        });
        return;
      }

      if (!this.info.password) {
        uni.showToast({
          duration: 1500,
          icon: 'none',
          title: '请填写完整资料',
        });
        return;
      }
      let noteStr = '';
      // if (!this.checkPswString(this.info.paypwd)) noteStr = '安全密码格式错误，密码只能由6-16位数字与字母组合，请重新填写';
      if (!this.checkPswString(this.info.password))
        noteStr = '登录密码格式错误，密码只能由6-16位数字与字母组合，请重新填写';
      if (noteStr) {
        uni.showToast({
          duration: 2000,
          icon: 'none',
          title: noteStr,
        });
        return;
      }
      // if (!this.info.parent) {
      //   uni.showToast({
      //     duration: 1500,
      //     icon: 'none',
      //     title: '请填写推荐人ID'
      //   });
      //   return;
      // }
      if (!this.agree) {
        uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '请先阅读并同意【广州商科注册协议】与【隐私协议】',
        });
        return;
      }
      // register
      if (!this.apiLoading) {
        this.apiLoading = true;
        this.apiUrl
          .submitRegister({
            data: {
              ...this.info,
              countryCode: this.countryCode,
            },
          })
          .then(
            (res) => {
              this.apiLoading = false;
              if (res.data.code == 0) {
                uni.showToast({
                  duration: 1500,
                  icon: 'none',
                  title: '注册成功',
                });

                // 分享合伙人消费者注册
                if (this.fromPaetnerINtroduction) {
                  uni.removeStorageSync('fromPaetnerINtroduction');
                  uni.setStorage({
                    data: true,
                    key: 'isFormEnter',
                    success: () => {
                      uni.navigateBack();
                    },
                  });
                }

                // #ifdef H5
                if (!this.isFormEnter) {
                  uni.navigateTo({
                    url: 'registerSuccess/registerSuccess',
                  });
                  return;
                }
                // #endif
                setTimeout(() => {
                  if (this.formPage == 'login') {
                    uni.navigateBack();
                  } else {
                    uni.navigateTo({
                      url: 'login',
                    });
                  }
                }, 1500);
              } else {
                uni.showToast({
                  duration: 1500,
                  icon: 'none',
                  title: res.data.message,
                });
              }
            },
            () => {
              this.apiLoading = false;
            }
          );
      }
    },
    getCode() {
      if (!this.allowGetCode) return;
      if (!this.info.mobilePhone) {
        this.showMessage({ title: '请输入手机号码' });
        return;
      }

      if (!this.info.imgCode) {
        this.showMessage({ title: '请输入图片验证码' });
        return;
      }

      this.allowGetCode = false;
      this.timeCountdown();

      const params = {
        mobilePhone: this.info.mobilePhone,
        verifyCode: this.info.imgCode,
        key: this.key,
        type: 1,
        countryCode: this.countryCode,
      };

      this.apiUrl
        .getCode({ data: params })
        .then((res) => {
          if (res.data.code == 0) {
            this.allowGetCode = false;
            this.showMessage({ title: '验证码已发送' });
            return;
          }
          return Promise.reject(res);
        })
        .catch((err) => {
          this.allowGetCode = true;
          clearTimeout(this.smsCodeTimer);
          this.initImgCode();

          if (!isObject(err)) return;

          if (err.data.status == 'timeout') {
            this.showMessage({ title: '获取验证码失败' });
            return;
          }

          this.showMessage({ title: err.data.message });
        });
    },
    timeCountdown() {
      if (!this.countDown) {
        this.countDown = 60;
        clearTimeout(this.smsCodeTimer);
        this.allowGetCode = true;
        return;
      }
      this.countDown--;
      this.smsCodeTimer = setTimeout(() => {
        this.timeCountdown();
      }, 1000);
    },
    initImgCode() {
      this.key = new Date().getTime();
      this.imgCodePath = config.baseUrl + '/member_veryCode.action?key=' + this.key;
      this.info.imgCode = '';
    },
  },
};
</script>

<style lang="less" scoped>
.c-navbar-no {
  padding-top: 88rpx;
}
.register {
  padding-left: 60rpx;
  padding-right: 60rpx;
}

.register-title {
  height: 62rpx;
  font-size: 44rpx;
  color: #333333;
  line-height: 62rpx;
  text-align: center;
  margin-bottom: 70rpx;
  padding-top: 40rpx;
}

.img-code {
  width: 150rpx;
  height: 70rpx;
  display: block;
  overflow: hidden;
}

.v-code {
  height: 37rpx;
  line-height: 37rpx;

  text {
    font-size: 26rpx;
    color: #1c4c98;
  }

  &.deny text {
    color: #b4b1aa;
  }
}

.agreement {
  display: flex;
  align-items: center;

  text {
    color: #656565;
    height: 40upx;
    font-size: 24rpx;
    line-height: 40upx;
    overflow: hidden;
  }

  .underline {
    color: #e64e2d;
    text-decoration: underline;
  }
}

.agreement-checkbox .icon {
  width: 32upx;
  height: 32upx;
  display: block;
}

.login-submit {
  height: 90rpx;
  background: #e64e2d;
  border-radius: 45px;
  line-height: 90rpx;

  font-size: 36rpx;
  color: #fff;
  line-height: 50rpx;
  line-height: 90rpx;
  margin-top: 110rpx;
  text-align: center;
  margin-bottom: 100rpx;
}
</style>

<style lang="less" scoped>
.country-code {
  height: 40rpx;
  border-right: 1px solid #b4b1aa;
  padding-right: 24rpx;
  margin-right: 24rpx;

  .picker {
    font-size: 34rpx;
    font-weight: 400;
    color: #333333;
    line-height: 40rpx;
  }
}
</style>
